package com.biannuo.szk.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 自定义全局过滤器
 * token认证
 *
 * @author szk
 */
//@Component
public class TokenGlobalFilter implements GlobalFilter, Ordered {
    /**
     * 为了模拟，此处写死token
     */
    private final String TOKEN_VALUE = "123456";

    /**
     * 业务逻辑处理的方法
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //得到token参数的值
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if (null != token) {
            // 判断token是否相等
            if (TOKEN_VALUE.equals(token)) {
                // 放行
                return chain.filter(exchange);
            }
        }
        //友好提示
        byte[] bytes = ("您不能访问" + exchange.getRequest().getPath() + "地址").getBytes(StandardCharsets.UTF_8);
        DataBuffer wrap = exchange.getResponse().bufferFactory().wrap(bytes);
        // 标记为不能访问的状态码（401，Unauthorized）
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        // 返回友好提示
        return exchange.getResponse().writeWith(Flux.just(wrap));
    }

    @Override
    public int getOrder() { // 排序 数值越小，优先级越高
        return 0;
    }
}
